package selenium.webedriver;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

import org.eclipse.jetty.util.log.Log;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.openqa.selenium.safari.SafariDriver;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriverException;
import org.openqa.selenium.interactions.Actions;
/*
 * Phoebe 
 * 2015/9/26
 * 
  	openBrowser
  	maximizeBrowserWindow
  	closeBrowser
 	forward
 	back
  	refresh
  	go
  	SwitchToDefaultContent
 	getTitle
  	getLocation
  	isTextPresent
  	getAlerttext
	isAlertPresent	
	switchWindowByName
	switchWindowByTitle
	closeWindowByTitle
	switchFrame
 */
import org.openqa.selenium.WebElement;

public class WebDriver {	
	private RemoteWebDriver driver;
	private List<WebElement> query;
	Map<String, String> KWResult = new HashMap<String, String>(); 
	
	public Map<String, String> openBrowser(String url,String browser,String alias) 
	{	
				   
		 if (!browser.contains("googlechrome") && !browser.contains("firefox") &&  !browser.contains("iexplore") && !browser.contains("safari") )
		 {
			 KWResult.put("result", "false");
			 KWResult.put("message", "This browser was not in supported list(firefox,googlechrome ,iexplore and safari)");
			 return KWResult;
		 }
		  
		 String chromedriver="";	
		 Properties prop = System.getProperties();
		 String os = prop.getProperty("os.name");				   
		 if (os.startsWith("win") || os.startsWith("Win"))
		 {      	    	 
					
			   if (browser.contains("googlechrome")) 
			   {
			        	
			        DesiredCapabilities capabilities = DesiredCapabilities.chrome();		
			        capabilities.setCapability("chrome.switches", Arrays.asList("--allow-running-insecure-content"));
					capabilities.setCapability("chrome.switches", Arrays.asList("--start-maximized"));
					System.setProperty("webdriver.chrome.driver", "C:\\Tool\\chromedriver.exe");
					driver = new ChromeDriver();			 
			   }
			   if (browser.contains("firefox")) 
			   {
				   System.setProperty("webdriver.firefox.bin", "C:/Program Files (x86)/Mozilla Firefox/firefox.exe");
				   driver = new FirefoxDriver(); 
			   }
			   if (browser.contains("iexplore")) 
			   {
				  	DesiredCapabilities capabilities = DesiredCapabilities.internetExplorer();
				  	driver = new InternetExplorerDriver ();					  	
			   }
		  }
		 if (driver==null)	                	
		 {				  		
		  	KWResult.put("result", "false");
			KWResult.put("message", "openBrowser execute failed ,because create dirver failed");
							
		 }
		 else
		 {
		  	driver.get(url);	
		  	KWResult.put("result", "true");
			KWResult.put("message", "openBrowser was executed successfully.");
					
		  	
		 }
		    	
		return KWResult;		 
		  
	}
	
	public Map<String, String> maximizeBrowserWindow()
	{
		try
		{  
			driver.manage().window().maximize(); 	
			KWResult.put("result", "true");
			KWResult.put("message", "maximizeBrowserWindow was executed successfully.");
			
	    }
		catch(Exception e){  
			KWResult.put("result", "false");
			KWResult.put("message", "maximizeBrowserWindow executed failed "+e.getMessage());				   
	    }
		return KWResult;
	}
	
	public Map<String, String> closeBrowser()
	{
		try
		{  			
			driver.close();			
			KWResult.put("result", "true");
			KWResult.put("message", "closeBrowser was executed successfully.");
			
	    }
		catch(Exception e){  
			KWResult.put("result", "false");
			KWResult.put("message", "closeBrowser executed failed "+e.getMessage());				   
	    }
		return KWResult;
	}
	
	public Map<String, String> forward()
	{
		try
		{  			
			driver.navigate().forward();	
			KWResult.put("result", "true");
			KWResult.put("message", "forward was executed successfully.");
	    }
		catch(Exception e){  
			KWResult.put("result", "false");
			KWResult.put("message", "forward executed failed "+e.getMessage());				   
	    }
		return KWResult;
	}
	
	public Map<String, String> back()
	{
		try
		{  			
			driver.navigate().back();
			KWResult.put("result", "true");
			KWResult.put("message", "back was executed successfully.");
	    }
		catch(Exception e){  
			KWResult.put("result", "false");
			KWResult.put("message", "back executed failed "+e.getMessage());				   
	    }
		return KWResult;
	}
	
	public Map<String, String> refresh()
	{
		try
		{  			
			driver.navigate().refresh();	
			KWResult.put("result", "true");
			KWResult.put("message", "refresh was executed successfully.");
	    }
		catch(Exception e){  
			KWResult.put("result", "false");
			KWResult.put("message", "refresh executed failed "+e.getMessage());				   
	    }
		return KWResult;
	}
	
	public Map<String, String> go(String url)
	{
		try
		{  			
			driver.navigate().to(url);	
			KWResult.put("result", "true");
			KWResult.put("message", "go was executed successfully.");
	    }
		catch(Exception e){  
			KWResult.put("result", "false");
			KWResult.put("message", "go executed failed "+e.getMessage());				   
	    }
		return KWResult;
	}
	
	public Map<String, String> SwitchToDefaultContent(String url)
	{
		try
		{  			
			driver.switchTo().defaultContent();	
			KWResult.put("result", "true");
			KWResult.put("message", "defaultContent was executed successfully.");
	    }
		catch(Exception e){  
			KWResult.put("result", "false");
			KWResult.put("message", "defaultContent executed failed "+e.getMessage());				   
	    }
		return KWResult;
	}
	
	public Map<String, String> getTitle()
	{
		String currenttitle="";
		try
		{  			
			currenttitle=driver.getTitle();	
			KWResult.put("title", currenttitle);
			KWResult.put("result", "true");
			KWResult.put("message", "getTitle was executed successfully.");

	    }
		catch(Exception e){  
			KWResult.put("result", "false");
			KWResult.put("message", "getTitle executed failed "+e.getMessage());	
			
	    }
		return KWResult;
	}
	
	public Map<String, String> getLocation()
	{
		String location="";
		try
		{  			
			location=driver.getCurrentUrl();	
			KWResult.put("location", location);
			KWResult.put("result", "true");
			KWResult.put("message", "getLocation was executed successfully.");
	    }
		catch(Exception e){  
			KWResult.put("result", "false");
			KWResult.put("message", "getCurrentUrl executed failed "+e.getMessage());	
			
	    }
		return KWResult;
	}
	
	public Map<String, String> isTextPresent(String text)
	{
		String bodysource="";
		boolean IsTextPresentflag=false;
		String result="";
		try
		{  		
			bodysource=driver.getPageSource();
			IsTextPresentflag = bodysource.contains(text);		
			result=Boolean.toString(IsTextPresentflag);
			KWResult.put("title",result);
			KWResult.put("result","true");
			KWResult.put("message", "isTextPresent was executed successfully.");
	    }
		catch(Exception e){  
			KWResult.put("result", "false");
			KWResult.put("message", "isTextPresent executed failed "+e.getMessage());	
			
	    }
		return KWResult;
	}
	
	public Map<String, String> isAlertPresent(String text)
	{
		boolean isAlertPresent=false;
		String result="";
		try
		{  		
			driver.switchTo().alert();
			isAlertPresent = true;		
			result=Boolean.toString(isAlertPresent);
			KWResult.put("isAlertPresent", result);
			KWResult.put("result","true");
			KWResult.put("message", "isAlertPresent was executed successfully.");
	    }
		catch(Exception e){  
			KWResult.put("result", "false");
			KWResult.put("message", "isAlertPresent executed failed "+e.getMessage());	
			
	    }
		return KWResult;
	}
	
	public Map<String, String> getAlerttext()
	{
		String alertText="";
		try
		{  			
			alertText=driver.switchTo().alert().getText();		;	
			KWResult.put("getAlerttext", alertText);
			KWResult.put("result","true");
			KWResult.put("message", "getAlerttext was executed successfully.");
	    }
		catch(Exception e){  
			KWResult.put("result", "false");
			KWResult.put("message", "getAlerttext executed failed "+e.getMessage());	
			
	    }
		return KWResult;
	}
	
	public Map<String, String> switchWindowByName(String name)
	{		
		try
		{  			
			driver.switchTo().window(name);
			KWResult.put("result","true");
			KWResult.put("message", "switchWindowByName was executed successfully.");
	    }
		catch(Exception e){  
			KWResult.put("result", "false");
			KWResult.put("message", "switchWindowByName executed failed "+e.getMessage());	
			
	    }
		return KWResult;
	}
	
	public Map<String, String> switchWindowByTitle(String windowTitle)
	{	
		boolean flag = false;
		try
		{  			
			 String currentHandle = driver.getWindowHandle();  
		        Set<String> handles = driver.getWindowHandles();  
		        for (String s : handles) {  
		            if (s.equals(currentHandle))  
		                continue;  
		            else {  
		                driver.switchTo().window(s);  
		                if (driver.getTitle().contains(windowTitle)) {  
		                    flag = true;           
		                    break;  
		                } else  
		                    continue;  
		            }  
		        }  
		        KWResult.put("result","true");
				KWResult.put("message", "switchWindowByTitle was executed successfully.");
	    }
		catch(Exception e){  
			KWResult.put("result", "false");
			KWResult.put("message", "switchWindowByTitle executed failed "+e.getMessage());	
			
	    }
		return KWResult;
	}
	
	public Map<String, String> closeWindowByTitle(String windowTitle)
	{	
		boolean flag = false;
		try
		{  			
			String currentHandle = driver.getWindowHandle();  
	        Set<String> handles = driver.getWindowHandles();  
	        for (String s : handles) {  
	            if (s.equals(currentHandle))  
	                continue;  
	            else {  
	                driver.switchTo().window(s).close();  
	                if (driver.getTitle().contains(windowTitle)) {  
	                    flag = true; 	                   
	                    break;  
	                } else  
	                    continue;  
	            }  
	        }  
	        KWResult.put("result","true");
			KWResult.put("message", "closeWindowByTitle was executed successfully.");
	    }
		catch(Exception e){  
			KWResult.put("result", "false");
			KWResult.put("message", "closeWindowByTitle executed failed "+e.getMessage());	
			
	    }
		return KWResult;
	}
	
	public Map<String, String> switchFrame(String name)
	{			
		try
		{  			
			driver.switchTo().frame(name);
			KWResult.put("result","true");
			KWResult.put("message", "switchFrame was executed successfully.");
		    
	    }
		catch(Exception e){  
			KWResult.put("result", "false");
			KWResult.put("message", "switchFrame executed failed "+e.getMessage());	
			
	    }
		return KWResult;
	}
	
	private List<WebElement> FindElement(String location)  
	{ 
		boolean findObjectFlag=false;
				
		if (location.startsWith("//"))
		{ 
			query= driver.findElements(By.xpath(location));				 
				    
		}
		else if(location.startsWith("id"))
		{ 
			String lcoationtmp=location.substring(3);					
			query= driver.findElements(By.id(lcoationtmp));				
		}
		else if(location.startsWith("name"))
	    {
		    String lcoationtmp=location.substring(5);		  	
		    query= driver.findElements(By.name(lcoationtmp));		    
	    }	
	    else if(location.startsWith("css"))
		{
	    	String lcoationtmp=location.substring(4);
			query= driver.findElements(By.cssSelector(lcoationtmp));
		}
			 
		else if(location.startsWith("tagName"))
		{
			String lcoationtmp=location.substring(8);
			query= driver.findElements(By.tagName(lcoationtmp));			   			
		 }		  
		 else if(location.startsWith("className"))
		 {   
			String lcoationtmp=location.substring(10);			  
			query= driver.findElements(By.className(lcoationtmp));			  
		 }
		 else if(location.startsWith("linktext"))
		 {   
			String lcoationtmp=location.substring(9);			  
			query= driver.findElements(By.linkText(lcoationtmp));			  
		 }
		 else if(location.startsWith("partialLinkText"))
		 {   
			String lcoationtmp=location.substring(16);			  
			query= driver.findElements(By.partialLinkText(lcoationtmp));			  
		 }
		 if (query.toArray().length > 1)
	     {   
			 findObjectFlag = true;
			 KWResult.put("result","true");
			 KWResult.put("message", "findElement was executed successfully and find more then one element.");
			 
	     }
		 
		 if (query.toArray().length == 1)
	     {   
			 findObjectFlag = true;
			 KWResult.put("result","true");
			 KWResult.put("message", "findElement was executed successfully and find this element.");
	     }
		 
	     if (query.toArray().length ==0)
	     {
	    	findObjectFlag = false;
	    	 KWResult.put("result","true");
			 KWResult.put("message", "Didn't find this element by location: "+location);
	     }
	    return query;		
	}
	
	public Map<String, String> click(String location)
	{
		
		try{  
			 Actions actions = new Actions(driver);
			 query=FindElement(location);			 
			 WebElement target=query.get(0);			 
			 actions.moveToElement(target);
			 actions.click();
			 actions.build().perform();	
			 KWResult.put("result","true");
			 KWResult.put("message", "click was executed successfully");
        }	
		 catch(Exception e){  
	            e.printStackTrace(); 
	            KWResult.put("result","false");
				KWResult.put("message", "click was executed failed and the failed reason is : "+e.getMessage());
	         }	
		return KWResult;		   
		   
	}
	
	public Map<String, String> type(String location,String text)
	{
		
		try{  
			 Actions actions = new Actions(driver);
			 query=FindElement(location);			 
			 WebElement target=query.get(0);			 
			 actions.moveToElement(target);
			 actions.sendKeys(text);
			 actions.build().perform();	
			 KWResult.put("result","true");
			 KWResult.put("message", "type was executed successfully");
        }	
		 catch(Exception e){  
	            e.printStackTrace(); 
	            KWResult.put("result","false");
				KWResult.put("message", "type was executed failed and the failed reason is : "+e.getMessage());
	         }	
		return KWResult;		   
		   
	}
	
	/*
	public static void main(String args[])
	{
		WebDriver wd = new WebDriver();
		wd.openBrowser("http://www.baidu.com", "firefox", "");
		wd.closeBrowser();
	}*/

}


